package controller

import (
	"context"
	pb "gitee.com/micro-services/protocol/verify/api"
	vpb "gitee.com/micro-services/protocol/verify/server"
	log "github.com/sirupsen/logrus"
	"micro.verify.client/plugins"
	"micro.verify.client/services"
)

type VerifyController struct{}

func (vc *VerifyController) GenerateCaptcha(ctx context.Context, r *pb.APIGenerateCaptchaReq, w *pb.APIGenerateCaptchaRsp) error {
	log.Printf("request:%+v", r)

	rsp, err := services.GetProxyManger().CaptchaServiceProxy.GenerateCaptcha(ctx, &vpb.GenerateCaptchaReq{
		Height:      r.Height,
		Width:       r.Width,
		CaptchaType: r.CaptchaType,
	})
	if err != nil {
		log.Printf("error:%+v", err)
		return err
	}

	w.CaptchaID = rsp.CaptchaID
	w.CaptchaCode = rsp.CaptchaCode

	return nil
}

func (vc *VerifyController) VerifyCaptcha(ctx context.Context, r *pb.APIVerifyCaptchaReq, w *pb.APIVerifyCaptchaRsp) error {
	log.Printf("request:%+v", r)

	rsp, err := services.GetProxyManger().CaptchaServiceProxy.VerifyCaptcha(ctx, &vpb.VerifyCaptchaReq{
		CaptchaID:   r.CaptchaID,
		CaptchaCode: r.CaptchaCode,
	})
	if err != nil {
		log.Printf("error:%+v", err)
		return err
	}

	w.Result = rsp.Result

	return nil
}

func (vc *VerifyController) SendEmail(ctx context.Context, r *pb.APISendEmailReq, w *pb.APISendEmailRsp) error {
	log.Printf("request:%+v", r)
	span, md, spanCtx := plugins.TracerContext(ctx, "SendEmail")

	rsp, err := services.GetProxyManger().EmailServiceProxy.SendEmail(spanCtx, &vpb.SendEmailReq{
		Receiver: r.Receiver,
	})
	if err != nil {
		log.Printf("error:%+v", err)
		plugins.TracerErrorInfo(span, "go.micro.api.user.SendEmail", md, r, w, rsp, err)
		return err
	}

	w.RetCode = rsp.RetCode
	w.Msg = rsp.Msg

	plugins.TracerFinish(span, "go.micro.api.verify.SendEmail", md, r, w)
	return nil
}

func (vc *VerifyController) VerifyCode(ctx context.Context, r *pb.APIVerifyCodeReq, w *pb.APIVerifyCodeRsp) error {
	log.Printf("request:%+v", r)
	span, md, spanCtx := plugins.TracerContext(ctx, "VerifyCode")

	rsp, err := services.GetProxyManger().EmailServiceProxy.VerifyCode(spanCtx, &vpb.VerifyCodeReq{
		Receiver:     r.Receiver,
		ReceiverCode: r.ReceiverCode,
	})
	if err != nil {
		log.Printf("error:%+v", err)
		plugins.TracerErrorInfo(span, "go.micro.api.verify.VerifyCode", md, r, w, rsp, err)
		return err
	}

	w.Result = rsp.Result
	plugins.TracerFinish(span, "go.micro.api.verify.VerifyCode", md, r, w)
	return nil
}
